/**游戏结算界面 */
class GameOver extends eui.Component {
	public constructor() {
		super();
		this.skinName = "resource/assets/skins/gameOverSkin.exml";
		st_config.setScreenAuto(this);
		this.init();
	}
	// /**单例 */
	private static instance: GameOver;
	public static getInstance(): GameOver {
		if (this.instance == null) {
			this.instance = new GameOver();
		}
		return this.instance;
	}
	/**分数 */
	public num: number;
	/**玩家名次 */
	public playerRank: number;
	/**控制添加试用 */
	public isGameover: boolean = false;
	/**商品管理类 */
	private m_gameShopMgr: gameShopView = new gameShopView(this);
	private gameAgain: eui.Image;

	/**分享按钮 */
	public fenxiang: eui.Image;
	/**战绩显示层 */
	private displayRecord: eui.Group;
	public static gameUser: any;
	private roomid = -1;
	/**当前页 */
	private currentPage: number;
	/**用户数据 */
	private userData = [];
	/**上一页 */
	private previousPage: eui.Image;
	/**下一页 */
	private nextPage: eui.Image;
	/**是否添加上页下页侦听 */
	private isUpDown: boolean = true;
	/**背景音乐 */
	private bgSound: soundMgr = new soundMgr();

	/**看视频奖励按钮 */
	public reward: eui.Image;

	private init() {
		this.gameAgain.touchEnabled = true;
		this.gameAgain.addEventListener(egret.TouchEvent.TOUCH_TAP, this.gameGoOn, this);
		this.fenxiang.addEventListener(egret.TouchEvent.TOUCH_TAP, this.dianfenxiang, this);
		this.reward.addEventListener(egret.TouchEvent.TOUCH_TAP, this.watchVideo, this);

	}
	/**奖励按钮呼吸效果 */
	private rewardButton() {
		this.reward.visible = true;
		egret.Tween.get(this.reward, { loop: true })
			.to({ scaleX: 0.7, scaleY: 0.7 }, 600)
			.to({ scaleX: 1, scaleY: 1 }, 600);
	}
	/**观看广告 */
	public async watchVideo() {
		wxtool.Instance.add = true;
		const isEnded = await platform.showVideo();
		wxtool.Instance.reward(isEnded);
		//wxtool.Instance.OpenAD("adunit-423aa89d6762dee9");
		egret.Tween.removeTweens(this.reward);
		this.reward.visible = false;
		console.log(wxtool.Instance.num);

	}
	/**点击分享 */
	public dianfenxiang() {
		this.fenxiang.visible = false;
		SoundManager.getInstance().playEffectSound("click_mp3");
		console.log("点击分享");
		weixinManager.getInstance().clikShare()
	}
	/**本地服务器加钱 */
	public addmoney(ss: number) {
		if (DataProl.isVisitor == false) {
			let value = 'accountId=' + DataProl.account + '&addMoney=' + ss;
			MiniNet.post(DataProl.shopaddr, '/shop_share', value, this, this.addMoneyCallback);
			console.log(ss);
		}
	}

	public addMoneyCallback(userMoneyData) {
		var userMoney = JSON.parse(userMoneyData.target.response);
		DataProl.userCurrentDressUp.userMoney = userMoney;
	};
	/**改变大小可见范围 */
	public changeVis(scal) {
		/**设置屏幕缩放比例 */
		//egret.Tween.get(this).to({ scaleX: scal, scaleY: scal }, 500);
		this.scaleX = this.scaleY = scal
	}

	/**返回大厅 */
	public backToHall() {
		SoundManager.getInstance().playEffectSound("click_mp3");
		this.bgSound.closeSound();
		webNetworkMananger.getInstance().gameSceneRec.backToHall();
		// if (webNetworkMananger.isServerMove)
		// 	webNetworkMananger.getInstance().SendMeesage('backToHall', DataProl.account);
		console.log("玩家: " + DataProl.account + "  离开游戏..");
		this.visible = false;

	}

	/**继续游戏 */
	public gameGoOn() {
		SoundManager.getInstance().playEffectSound("click_mp3");
		webNetworkMananger.getInstance().gameSceneRec.isUserDied = false;
		this.visible = false;
		var useData = {
			"roomId": DataProl.roomid,
			"account": DataProl.account
		};
		if (webNetworkMananger.isServerMove) {
			let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
			let m_c2sRespawn = new awesomepackage.c2sRespawn();
			m_c2sRespawn.account = DataProl.account;

			m_c2sRespawn.sign = DataProl.sign;
			m_c2sRespawn.roomId = DataProl.roomid;
			m_AwesomeMessage.meesageId = 1006;
			m_AwesomeMessage.data = awesomepackage.c2sRespawn.encode(m_c2sRespawn).finish();

			var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
			var byte2: egret.ByteArray = new egret.ByteArray(buffer);
			webNetworkMananger.getInstance().SendBitMeesage(byte2);

			var user = webNetworkMananger.getInstance().gameSceneRec.m_createAllFrogs.findFrogById(DataProl.account);
			user.reset();
			setTimeout(() => {
				user.OnresetShadowFogPoint(user);///**重置影子青蛙的位置 */
			}, 300);

		}
		//		webNetworkMananger.getInstance().SendMeesage('respawn', useData);
		else {
			webNetworkMananger.getInstance().gameSceneRec.gameAgain();
		}

		//this.bgSound.closeSound();
		//this.bgSound.playerSound("resource/assets/sound/onclick.WAV", 1);
	}

	/**更改用户成就进度 */
	private changeUserRecord(userdata) {
		/**线长 */
		let lineLength = 0;
		/**VIP局数 */
		let vipNumber = 0;
		/**体重比例 */
		let weight = webNetworkMananger.getInstance().gameSceneRec.m_createAllFrogs.findFrogById(DataProl.account).scaleX;
		for (let i = 0; i < userdata.length; i++) {
			if (userdata[i].name == gameGlobal.global.playerName) {
				//获取线长
				lineLength = userdata[i].tongueLength;
				//获取是否是vip
				if (i == 0) {
					vipNumber++;
				}
				break;
			}
		}
		GlobalData.usrRecorData.KillNumber += DataProl.struckSeveral;
		GlobalData.usrRecorData.LineLength += lineLength;
		GlobalData.usrRecorData.InvoteFriends += DataProl.invoteFriends;
		GlobalData.usrRecorData.Weight += weight;
		GlobalData.usrRecorData.VipNumbers += vipNumber;
		var data = {
			KillNumber: GlobalData.usrRecorData.KillNumber,
			LineLength: GlobalData.usrRecorData.LineLength,
			InvoteFriends: GlobalData.usrRecorData.InvoteFriends,
			Weight: GlobalData.usrRecorData.Weight,
			VipNumbers: GlobalData.usrRecorData.VipNumbers,
			accountId: DataProl.account
		};
		//发送测试代码
		MiniNet.post(DataProl.shopaddr, '/changeUserRecord', 'data=' + JSON.stringify(data), this, this.changeUserRecordCallBack);
	}
	/**更改用户进度回调 */
	private changeUserRecordCallBack(usrRecorData) {
		var RecoData = JSON.parse(usrRecorData.target.response);
		if (RecoData.shopData) {
			this.getRecorfToMedal(GlobalData.usrRecorData);
			this.restAchievementData();
		}
		console.log("更改记录成功记录数" + RecoData);
	}
	/**初始化成就数据 */
	public restAchievementData() {
		DataProl.isEvenLine = false;
		DataProl.connectionNumber = [];
		DataProl.struckSeveral = 0;
		DataProl.invoteFriends = 0
	}
	/**根据进度获取相应的勋章 */
	public getRecorfToMedal(RecoData) {
		let goodsId = 0;

		//1001黑框眼镜（百人斩）
		if (parseInt(RecoData.KillNumber) >= GlobalData.attainmentTargets.KillNumber) {
			if (!this.checkIsHaveMedal(1001)) {
				goodsId++;
			}
		}

		if (DataProl.connectionNumber.length > 0) {
			//1003心形眼镜（一局跟玩家没断过线）
			if (DataProl.connectionNumber.length == 1) {
				if (!this.checkIsHaveMedal(1003)) {
					goodsId++;
				}
			}
			//1002绿色眼镜（和所有玩家连过线）
			if (DataProl.connectionNumber.length >= 9) {
				if (!this.checkIsHaveMedal(1002)) {
					goodsId++;
				}
			}
		}

		//1004闪光眼镜（没有和任何玩家连线）
		if (!DataProl.isEvenLine) {
			if (!this.checkIsHaveMedal(1004)) {
				goodsId++;
			}
		}

		//1005花花眼镜（累计线长10000米）
		if (parseInt(RecoData.LineLength) >= GlobalData.attainmentTargets.LineLength) {
			if (!this.checkIsHaveMedal(1005)) {
				goodsId++;
			}
		}

		//2001心形拖尾（100局第一）
		if (parseInt(RecoData.VipNumbers) >= GlobalData.attainmentTargets.VipNumbers) {
			if (!this.checkIsHaveMedal(2001)) {
				goodsId++;
			}
		}

		//2002星星拖尾（最大体重超过1000）
		if (parseInt(RecoData.Weight) >= GlobalData.attainmentTargets.Weight) {
			if (!this.checkIsHaveMedal(2002)) {
				goodsId++;
			}
		}

		//2003桃花拖尾（邀请好友进行游戏10次）
		if (parseInt(RecoData.InvoteFriends) >= GlobalData.attainmentTargets.InvoteFriends) {
			if (!this.checkIsHaveMedal(2003)) {
				goodsId++;
			}
		}

		if (goodsId > 0) {
			this.changeUserSkin();
		}
	}
	/**改变用户皮肤状态 */
	public changeUserSkin() {
		let skinStates = [];
		for (let i = 0; i < GlobalData.userShopData.length; i++) {
			var skinChangeData1 = {
				accountId: DataProl.account,
				shopId: parseInt(GlobalData.userShopData[i].shopId),
				states: parseInt(GlobalData.userShopData[i].states)
			};
			skinStates.push(skinChangeData1);
		}
		//发送测试代码
		MiniNet.post(DataProl.shopaddr, '/setUserSkinStates', 'data=' + JSON.stringify(skinStates), this, this.setUserSkinCallBack);
	}
	/**更改皮肤状态成功回调 */
	private setUserSkinCallBack(usrRecorData) {
		var shopsData = JSON.parse(usrRecorData.target.response);
		if (shopsData.shopData == true) {
			console.log("更改皮肤成功" + shopsData);
		}
		else {
			console.log("更改皮肤失败" + shopsData);
		}
	}
	/**判断是否拥有此勋章 */
	public checkIsHaveMedal(goodId) {
		for (let i = 0; i < GlobalData.userShopData.length; i++) {
			if (parseInt(GlobalData.userShopData[i].shopId) == goodId) {
				if (parseInt(GlobalData.userShopData[i].states) > 0) {
					return true;
				} else {
					GlobalData.userShopData[i].states = "1";
					return false;
				}
			}
		}
		return true;

	}
	/**显示战绩 */
	public showTops(userdata) {
		this.rewardButton();
		if (webNetworkMananger.isServerMove) {
			this.changeUserRecord(userdata);
		}
		this.currentPage = 1;
		webNetworkMananger.getInstance().gameSceneRec.isUserDied = true;
		if (userdata != null) {
			if (userdata.length > 0) {
				userdata.sort(function (a, b) { return b.grade - a.grade; });
				this.userData = [];
				//算两队总击杀数
				if (DataProl.tuanduizhan) {
					/**绿队总击杀 */
					var lvzhanji = 0;
					/**黄队总击杀 */
					var huangzhanji = 0
					for (let i = 0; i < userdata.length; i++) {
						if (userdata[i].troops == 0) {
							lvzhanji += userdata[i].killNumber
						}
						else {
							huangzhanji += userdata[i].killNumber
						}
					}
				}
				//青蛙数据处理
				for (let i = 0; i < userdata.length; i++) {
					//跟历史最高长度比较存战绩
					if (userdata[i].userId == DataProl.account) {
						if (DataProl.isVisitor == false) {
							if (userdata[i].grade > DataProl.maxLong) {
								DataProl.maxLong = userdata[i].grade;
								console.log("存战绩:" + userdata[i].grade);
								let value = 'userid=' + DataProl.account + '&maxLong=' + DataProl.maxLong + '&name=' + gameGlobal.global.playerName;
								MiniNet.post(DataProl.loginaddr, '/wechat/update', value, this, this.sendMsg);
							}
						}
					}
					var data;
					if (webNetworkMananger.isServerMove) {
						data = {
							name: userdata[i].name,
							lineLength: userdata[i].tongueLength
						}
					} else {
						data = {
							name: userdata[i].name,
							grade: userdata[i].grade,
							userId: userdata[i].userId,
							troops: userdata[i].troops,
							killNumber: userdata[i].killNumber
						}
					}
					if (DataProl.tuanduizhan) {//是团队战，先排绿队
						if (data.troops == 0) {
							//添加绿队队名
							if (this.userData.length == 0) {
								var mm = {
									name: "绿队",
									lineLength: lvzhanji,
									userId: 0,
									troops: 0
								}
								this.userData.push(mm);
							}
							//添加绿队青蛙
							this.userData.push(data);
						}
					}
					else {
						this.userData.push(data);//不是团队战
					}
				}
				if (DataProl.tuanduizhan) {//是团队战，再排黄队
					for (let i = 0; i < userdata.length; i++) {
						var da = {
							name: userdata[i].name,
							lineLength: userdata[i].lineLength,
							userId: userdata[i].userId,
							troops: userdata[i].troops,
							killNumber: userdata[i].killNumber
						}
						if (da.troops == 1) {
							//添加黄队队名
							if (this.userData.length == 6) {
								var mm = {
									name: "黄队",
									lineLength: huangzhanji,
									userId: 0,
									troops: 1
								}
								this.userData.push(mm);
							}
							//添加黄队青蛙
							this.userData.push(da);
						}
					}
				}
				this.displayRecord.removeChildren();
				this.displayPartOfTheRecord(this.userData, 1);
				for (var i = 0; i < this.userData.length; i++) {
					if (this.userData[i].userId == DataProl.account) {
						if (DataProl.isVisitor) {
							break;
						}
						else {
							if (this.userData[i].userId == this.userData[0].userId) {
								this.addmoney(10);
								wxtool.Instance.num = 1;
								// console.log("结束1");
								break;
							}
							if (this.userData[i].userId == this.userData[1].userId) {
								this.addmoney(5);
								wxtool.Instance.num = 2;
								// console.log("结束2");
								break;
							}
							if (this.userData[i].userId == this.userData[2].userId) {
								this.addmoney(3);
								wxtool.Instance.num = 3;
								// console.log("结束3");
								break;
							} else {
								this.addmoney(2);
								wxtool.Instance.num = 4;
								// console.log("结束4");
								break;
							}

						}

					}
				}
			}
		}

		if (this.isUpDown) {
			console.log(123211);

			//上一页点击事件
			this.previousPage.addEventListener(egret.TouchEvent.TOUCH_TAP, e => {
				if (this.currentPage <= 1) {
					return;
				} else {
					this.displayRecord.removeChildren();
					this.displayPartOfTheRecord(this.userData, this.currentPage - 1);
					this.currentPage--;
				}
			}, this);
			//下一页点击事件
			this.nextPage.addEventListener(egret.TouchEvent.TOUCH_TAP, e => {
				if (this.currentPage > 2) {
					return;
				} else {
					this.displayRecord.removeChildren();
					//this.userData.sort(function (a, b) { return b.lineLength - a.lineLength; });
					this.displayPartOfTheRecord(this.userData, this.currentPage + 1);
					this.currentPage++;
				}
			}, this);
			this.isUpDown = false;
		}


	}
	/**显示部分战绩
	 * startIndex endIndex 显示区间
	 */
	private displayPartOfTheRecord(userdata, currentPage) {

		var startIndex = 0;
		var endIndex = 7;
		/**起始下标 */
		var prev: number;
		if (currentPage == 1) {
			prev = 0;
		} else {
			prev = 8;
		}
		DataProl.dei = 0;//一局内死亡次数清零
		for (var t = 0; t < userdata.length; t++) {
			if (t < startIndex || t > endIndex)
				continue;
			var point = { x: 25, y: 25 + t * 50 };
			this.displayOnePlayerRecord(userdata[prev + t], point);
			//console.log(userdata[t].userId+"玩家ID"+DataProl.account);
			if (prev + t > userdata.length - 1) {
				continue;
			}
		}
	}
	/**向开放数据域通信(发送战绩) */
	private sendMsg(n) {
		if (weixinManager.getInstance().getCode() != null) {
			let platform: any = window.platform;
			platform.openDataContext.postMessage({
				score: DataProl.maxLong.toString()
			});
		}
		// let openDataContext = wx.getOpenDataContext();
		// 	openDataContext.postMessage({
		// 	score: n.toString()
		// });
	}

	/**显示一个玩家的战绩 
	 * data  数据
	 * point 位置
	*/
	private displayOnePlayerRecord(data, point) {
		if (data == null || data == undefined) {
			return;
		}
		if (DataProl.tuanduizhan) {//如果是团队战添加队名
			var dui: eui.Label = new eui.Label()
			console.log("青蛙·线长" + data.lineLength + "青蛙名字" + data.name + "青蛙·颜色" + data.frogType);

			if (data.troops == 1) {
				dui.text = "匪徒"
			} else if (data.troops == 0) {
				dui.text = "警察"
			}
			dui.width = 200;
			dui.height = 30;
			dui.x = point.x - 100;
			dui.y = point.y;
			this.displayRecord.addChild(dui);
		}
		/**获得金币 */
		var jinbi: eui.Label = new eui.Label();
		for (var i = 0; i < this.userData.length; i++) {
			if (data.userId == this.userData[0].userId) {
				jinbi.text = "10";
				break;
			}
			if (data.userId == this.userData[1].userId) {
				jinbi.text = "5";
				break;
			}
			if (data.userId == this.userData[2].userId) {
				jinbi.text = "3";
				break;
			} else {
				jinbi.text = "2";
				break;
			}
		}
		jinbi.width = 100;
		jinbi.height = 30;
		jinbi.x = point.x + 500;
		jinbi.y = point.y;
		this.displayRecord.addChild(jinbi);
		if (data.userId == DataProl.account) {
			if (DataProl.isVisitor) {
				jinbi.text = "游客";
			}
			else {
				// if (data.userId == this.userData[0].userId) {
				// 	this.addmoney(10);
				// 	GameOver.playerRank = 1;
				// 	console.log("结束1");
				// }
				// else if (data.userId == this.userData[1].userId) {
				// 	this.addmoney(5);
				// 	GameOver.playerRank = 2;
				// 	console.log("结束2");
				// }
				// else if (data.userId == this.userData[2].userId) {
				// 	this.addmoney(3);
				// 	GameOver.playerRank = 3;
				// 	console.log("结束3");
				// } else {
				// 	this.addmoney(2);
				// 	console.log("结束4");
				// }

				//jinbi.textColor = 0xFFD700;
				//labelRecord.textColor = 0xFFD700;
				//labelScore.textColor = 0xFFD700;
				if (DataProl.tuanduizhan)
					dui.textColor = 0xFFD700;
			}

		}
		/**名字 */
		var labelRecord: eui.Label = new eui.Label();
		if (data.name.length > 10)
			data.name = data.name.substring(0, 10);
		labelRecord.text = data.name;
		labelRecord.width = 300;
		labelRecord.height = 30;
		labelRecord.x = point.x;
		labelRecord.y = point.y;
		labelRecord.fontFamily = 'Microsoft YaHei';
		this.displayRecord.addChild(labelRecord);
		/**战绩 */
		var labelScore: eui.Label = new eui.Label();
		labelScore.text = data.grade;
		labelScore.width = 100;
		labelScore.height = 30;
		labelScore.x = point.x + 300;
		labelScore.y = point.y;
		labelScore.fontFamily = 'Microsoft YaHei';
		this.displayRecord.addChild(labelScore);
		if (data.userId == DataProl.account) {
			labelRecord.textColor = 0xFFD700;
			labelScore.textColor = 0xFFD700;
			jinbi.textColor = 0xFFD700;
			if (DataProl.tuanduizhan)
				dui.textColor = 0xFFD700;
		}
		//console.log("玩家试用num"+gameShopData.getInstance().trynum);

		if (DataProl.userCurrentDressUp.decorateId == gameShopData.getInstance().trynum) {
			wxtool.Instance.hideTrying = true;
			console.log(wxtool.Instance.hideTrying);

			/**关闭试用中 */
			if (wxtool.Instance.hideTrying == true) {
				gameShopData.getInstance().m_gameShopMgr.hideTrying();

			}
		}

	}

}